/*
 * Copyright 2008 by Emeric Vernat
 *
 *     This file is part of MSwing.
 *
 * MSwing is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MSwing is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with MSwing.  If not, see <http://www.gnu.org/licenses/>.
 */
package mswing;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;

import javax.swing.RepaintManager;

/**
 * Contournement Sun bug 6209673 du JRE. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6209673
 * You must keep a strong reference to the DisplayChangedListener, since SunDisplayChanger keeps
 * only a WeakReference to it.
 *
 * @author Emeric Vernat
 */
public class DisplayChangeHandler implements sun.awt.DisplayChangedListener, Runnable {
	/**
	 * Constructeur.
	 */
	public DisplayChangeHandler() {
		super();
		try {
			final GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
			// Add ourselves as a listener to the GraphicsEnvironment if
			// possible.
			env.getClass().getMethod("addDisplayChangedListener",
					new Class[] { sun.awt.DisplayChangedListener.class }).invoke(env,
					new Object[] { this });
		} catch (final Throwable t) {
			MUtilities.printStackTrace(t);
		}
	}

	/** {@inheritDoc} */
	public void displayChanged() {
		EventQueue.invokeLater(this);
	}

	/** {@inheritDoc} */
	public void paletteChanged() {
		EventQueue.invokeLater(this);
	}

	/** {@inheritDoc} */
	public void run() {
		// Force the RepaintManager to clear out all of the VolatileImage
		// back-buffers that it has cached.
		// See Sun bug 6209673.
		final RepaintManager rm = RepaintManager.currentManager(null);
		final Dimension size = rm.getDoubleBufferMaximumSize();
		rm.setDoubleBufferMaximumSize(new Dimension(0, 0));
		rm.setDoubleBufferMaximumSize(size);
	}
}
